<script>
	export default {
		data() {
			return {
				// userInfo: [],
				isWeixin: false
			}
		},
		globalData: {
			userInfo: []
		},
		onLaunch() {
			this.isWeixin = this.isWechat()
			if (this.isWeixin && !uni.getStorageSync('token')) {
				this.checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
			}
		},
		onShow() {
			if (uni.getStorageSync('token')) {
				this.getUserInfo().then((res) => {
					if (res.code == 200) {
						this.globalData.userInfo = res.data	
					}
					this.$isResolve()
				})
			}
		},
		methods: {
			//方法：用来判断是否是微信内置的浏览器
			isWechat() {
				return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			},
			//方法:用来提取code
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||
				[, ''
				])[1].replace(/\+/g, '%20')) || null
			},
			//检查浏览器地址栏中微信接口返回的code
			checkWeChatCode() {
				let code = this.getUrlCode('code')
				if (code) {
					this.getOpenidAndUserinfo(code)
				} else {
					this.login()
				}
			},
			//请求微信接口，用来获取code
			login() {
				if (!this.isWeixin) {
					return uni.showToast({
						title: '请用微信浏览器打开',
						duration: 3000,
						icon: 'none'
					});
				}
				let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
				// let appid = 'wx3d4397bd9c361563'
				let appid = 'wxc789ca9b8e22e23b'

				//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				window.location.href =
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
					appid +
					"&redirect_uri=" +
					local +
					"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			},
			//把code传递给后台接口，静默登录
			getOpenidAndUserinfo(code) {
				let that = this;
				let data = {
					'code': code
				}
				uni.request({
					url: '/api/wechat/login', //仅为示例，并非真实接口地址。
					data: data,
					header: {

					},
					success: (json) => {
						// console.log(json.data);
						let res = json.data;
						if (res.code == 200) {
							uni.showToast({
								title: res.msg,
								duration: 3000,
								icon: 'none'
							});
							uni.setStorageSync('token', res.data.token)
							this.getUserInfo().then((res) => {
								if (res.code == 200) {
									this.globalData.userInfo = res.data
									
								}
								this.$isResolve()
							})
						}
					}
				});
			},
			getUserInfo() {
				return new Promise((resolve, reject) => {
					let url = '/api/user/getMyself';
					uni.request({
						url: url, //仅为示例，并非真实接口地址。
						header: {
							'token': uni.getStorageSync('token'),
						},
						success: (json) => {
							// console.log(json.data);
							let res = json.data;
							resolve(res);

						}
					});

				})


			}
		}
	}
</script>



<style>
	/*每个页面公共css */
	::-webkit-scrollbar{ display: none; }
	.image-view-img{
		width: 100%;
	}
</style>
